package net.keebook.webapp.ws;

import java.util.UUID;

import javax.ejb.Stateless;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import net.keebook.webapp.entity.User;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;


@Path("/{username}/getsalt")
@Stateless
public class GetSaltService extends WebService {
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String saveSettings(
			@PathParam("username") String username,
			@DefaultValue("") @QueryParam("password") String password)
	{	
		Logger.getLogger(this.getClass()).info("Incoming request");
		JSONObject result = new JSONObject();
		try {
			// Authentication
			User user = authenticate(username, password);
			if (user == null) {
				Logger.getLogger(this.getClass()).warn("Authentication failed for user " + username);
				result.put("authSuccess", false);
				result.put("success", false);
				return getResponse(result);
			}
			
			Logger.getLogger(this.getClass()).info("User " + username + " authenticated successfully (user id: "+user.getExposableId()+")");
			result.put("authSuccess", true);
			
			String salt = UUID.randomUUID().toString();
			result.put("salt", salt);
			result.put("success", true);
			
			Logger.getLogger(this.getClass()).info("Responding with generated salt: " + salt);
		} catch (JSONException e) {
			return getResponse(ERROR_RESPONSE);
		}
		
		return getResponse(result);
	}
}
